import { createI18n } from "vue-i18n";
import { getLocalStorage } from "@/utils/localStorage";

// element-plus 国际化文件
import element_zh from "element-plus/es/locale/lang/zh-cn";
import element_en from "element-plus/es/locale/lang/en";

export const getModuleByMetaGlob = (modules: any) => {
  let resources: any = {};
  if (!modules) return {};

  Object.keys(modules).forEach((key: string) => {
    if (modules[key].default) {
      const urlArr = key.split("/");
      const matched = key.match(/([A-Za-z0-9-_]+)\./i);
      if (matched && matched.length > 1) {
        const dirName: string = urlArr.splice(-2, 1)[0]; // 获取目录名
        const context = modules[key].default;

        resources[dirName] = context;
      }
    }
  });

  return resources;
};

export const getLocale = () => {
  const language =
    getLocalStorage("lang") ||
    getLocalStorage("language") ||
    navigator.language.toLowerCase();
  const locales = Object.keys(messages);
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      return locale;
    }
  }
  return "zh";
};

// 国际化文件
const locale_zh = getModuleByMetaGlob(
  import.meta.glob("./locales/**/zh.ts", { eager: true })
);
const locale_en = getModuleByMetaGlob(
  import.meta.glob("./locales/**/en.ts", { eager: true })
);

export const messages = {
  zh: {
    langName: "简体中文",
    ...element_zh,
    ...locale_zh,
  },
  en: {
    langName: "English",
    ...element_en,
    ...locale_en,
  },
};

export const i18n = createI18n({
  locale: getLocale(),
  fallbackLocale: "zh",
  globalInjection: true,
  messages,
});

export default i18n;
